﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TournamentDatabase.Objects;
using TournamentDatabase.Database;
using TournamentDatabase.Singletons;

namespace TournamentDatabase.Views
{
	/// <summary>
	/// Interaction logic for ResultsView.xaml
	/// </summary>
	public partial class ResultsView : Window
	{
		StringBuilder m_resBuilder;

		public string ResultsText
		{
			get { return m_resBuilder.ToString(); }
		}

		public ResultsView(Tournament tournament)
		{
			InitializeComponent();

			m_resBuilder = new StringBuilder();

			this.DataContext = this;

			tournamentResultsLabel.Content = tournament.Title;

			ProcessTournamentResults(tournament);
		}

		private void ProcessTournamentResults(Tournament tournament)
		{
			m_resBuilder.AppendLine("Results for tournament: " + tournament.Title);

			List<Competition> comps;

			comps = DatabaseSingleton.GetDatabaseAccessor().QueryCompetition("tid = " + tournament.TournamentID, OrderBy.None, "");

			foreach (Competition comp in comps)
			{
				ProcessCompetitionResults(comp);
			}
		}

		private void ProcessCompetitionResults(Competition competition)
		{
			m_resBuilder.AppendLine("\tResults for competition: " + competition.Type);

			List<CompetesIn> placings;

			string where = string.Format("tid = {0} AND type = '{1}' AND minBirthDate = TO_DATE('{2}','DD/MM/YYYY') AND maxBirthDate = TO_DATE('{3}','DD/MM/YYYY') AND gender = '{4}'",
				competition.TournamentID,
				competition.Type,
				// TODO: Format these dates correctly...
				competition.MinBirthDate,
				competition.MaxBirthDate,
				competition.Gender);


			placings = DatabaseSingleton.GetDatabaseAccessor().QueryCompetesIn(where, OrderBy.Ascending, "placing");

			foreach (CompetesIn placing in placings)
			{
				m_resBuilder.AppendLine(string.Format("\t\t{0:D3} - {1}, {2}", placing.Placing, placing.ArenaName, placing.Name));
			}
		}
	}
}
